package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.dao.LoginPersonDao;
import com.example.demo.entity.LoginPerson;
import com.example.demo.pojo.HttpResponseBody;
import com.example.demo.pojo.Token;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.apache.logging.log4j.Logger;
import java.util.Optional;

@RestController
public class LoginController {
    private static final Logger logger = LogManager.getLogger(LoginController.class);

    @Autowired
    private LoginPersonDao loginPersonDao;

    @PostMapping("login")
    public HttpResponseBody Login(String json){
        HttpResponseBody responseBody = new HttpResponseBody();

        LoginPerson originLoginPerson = JSON.parseObject(json,LoginPerson.class);
        String personCode = originLoginPerson.getPersonCode();
        String password = originLoginPerson.getPassword();

        Optional<LoginPerson> loginPersonOptional = loginPersonDao.findByPersonCode(personCode,password);
        if(!loginPersonOptional.isPresent()){
            logger.info("账号不存在或密码错误！");
            responseBody.setLogicError(false);
            responseBody.setMessage("账号不存在或密码错误！");
            return responseBody;
        }else {
            LoginPerson loginPersonResult = loginPersonOptional.get();
            logger.info(loginPersonResult.getPersonCode()+"登陆成功");
            responseBody.setLogicError(true);
            responseBody.setMessage("登录成功");
            Token token = new Token();
            token.setToken("ABCD");
            token.setUserID(loginPersonOptional.get().getId());
            responseBody.setResponseData(token);
            return responseBody;
        }
    }
}
